package yxy.game.pm2.command.arena;

import org.joda.time.DateTime;
import yxy.cherry.data.bean.arenadate;
import yxy.cherry.data.script.fomula;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ArenaMessage;
import yxy.game.pm2.module.arena.ArenaHandle;
import yxy.game.pm2.module.arena.ArenaPlayerModule;
import yxy.game.pm2.module.arena.RankArena;

/** 竞技场 挑战界面 */
@MessageType(proto = Command.ArenaChanllengeUI, classtype = ArenaMessage.ArenaChanllengeUIRequest.class)
public class CMD_ArenaChanllengeUI extends Command<ArenaMessage.ArenaChanllengeUIRequest> {

	@Override
	public void execute(MessageSource messageSource, ArenaMessage.ArenaChanllengeUIRequest request) {
		String playerCode = messageSource.getTag();

		ArenaMessage.ArenaChanllengeUIResponse.Builder response = ArenaMessage.ArenaChanllengeUIResponse.newBuilder();
		try {
			ArenaPlayerModule module = ArenaPlayerModule.get(playerCode);
			if (module == null) {
				send(messageSource, response, Result.ModuleNotOpen);// 竞技场模块没有开启
				return;
			}
			arenadate data = new ArenaHandle().data(0);
			long costNumber = Currency.number(playerCode, CurrencyType.forNumber(data.getCosttype()), data.getCostid(),false);
			int times = module.times();

			RankArena rankArena = RankArena.getRank(playerCode);
			RankEntry rankEntry = rankArena.get(playerCode);
			long score = 0;
			if (rankEntry == null) {
				score = fomula.竞技场初始分数.intValue();
			} else {
				score = rankEntry.getValue();
			}
			int rank = rankArena.rank(playerCode);

			long endTime = DateTime.now().withTimeAtStartOfDay().withDayOfWeek(1).plusWeeks(1).getMillis();
			response.setScore(score);
			response.setRank(rank);
			response.setItemNum(costNumber);
			response.setTimes(times < 0 ? 0 : times);
			response.setEndtime(endTime);
			response.setWeektimes(module.getWeektimes());
			response.setSkip(module.isSkip());
			for (String boxCode : module.getWeekbox()) {
				response.addWeekbox(Integer.valueOf(boxCode));
			}

			response.addAllOppo(new ArenaHandle().getOppo(playerCode));

			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}
	}

	private void send(MessageSource messageSource, ArenaMessage.ArenaChanllengeUIResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}